/**
 * Created by yangxianming on 2020/12/30.
 */
//
//接口定义 都是以api开头 所需参数都通过方法传入
//function apiGetCorpList(dofun, envText){}
//

function apiShowAnswerList(){
    var year = document.getElementById("year").value;
    var surveyName = document.getElementById("surveyName").value;
    var value = "action=getAnswerList&date="+year+"&surveyName="+surveyName;
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.open("get", "/survey/surveyUser?"+value, true);
    xmlHttp.onreadystatechange = function(){
        if (xmlHttp.readyState==4){
            if (xmlHttp.status==200){
                var r = JSON.parse(xmlHttp.response);
                if (r["apiStatus"] == "1"){
                    drawAnswerList(r["result"])
                }else{
                    alert("获取失败")
                }
            }
        }
    };
    xmlHttp.send();

}

//获取问卷列表 包括id，问卷名
function apiGetSurveyList(){
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.open("get", "/survey/getSurveyList?action=getList", true);
    xmlHttp.onreadystatechange = function(){
        if (xmlHttp.readyState==4){
            if (xmlHttp.status==200){
                var r = JSON.parse(xmlHttp.response);
                if (r["apiStatus"] == "1"){
                    drawSurveyList(r["result"])
                }else{
                    alert("获取失败")
                }
            }
        }
    };
    xmlHttp.send();
}

//保存问卷
function apiSaveSurvey(){
    var s_name = document.getElementById("s_name").value;
    var s_list = document.getElementById("s_list").getElementsByTagName("input");
    var s_list_data = [];
    for(var i = 0; i < s_list.length; i++){
        if(s_list[i].value.trim() == ""){
            continue;
        }
        s_list_data.push(s_list[i].value);
    }
    var saveData = {"action": "saveSurvey"};
    saveData["data"] = {
        "s_name":s_name,
        "s_list":s_list_data
    };
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.open("post", "/survey/saveSurvey", true);
    xmlHttp.onreadystatechange = function(){
        if (xmlHttp.readyState==4){
            if (xmlHttp.status==200){
                var r = JSON.parse(xmlHttp.response);
                if (r["apiStatus"] == "1"){
                    controlTopDivSurvey('createSurvey', 'close', '');
                }else{
                    alert("保存失败")
                }
            }
        }
    };
    xmlHttp.send(JSON.stringify(saveData));
}

//查询问卷的可用数，并发起各种形式的问卷，比如直接链接，或者钉钉
function apiGetOneSurvey(sidNode){
    var sid = sidNode.getAttribute("sid");
    var surveyName = sidNode.previousSibling.innerText;
    controlGenerateSurvey('generateSurvey', 'close', '');
    controlSendSurvey('sendSurvey', 'open', '对【'+surveyName+'】查询可用并推送问卷');
    document.getElementById("sendSurveyTitle").setAttribute("sid", sid);

    var uri = "action=getAvailableSurvey&surveyId="+sid;
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.open("get", "/survey/getSurveyList?"+uri, true);
    xmlHttp.onreadystatechange = function(){
        if (xmlHttp.readyState==4){
            if (xmlHttp.status==200){
                var r = JSON.parse(xmlHttp.response);
                if (r["apiStatus"] == "1"){
                    drawAvailableSurveyList(sid, r["result"]);
                }else{
                    alert("获取失败")
                }
            }
        }
    };
    xmlHttp.send();
}
//发送钉钉推送
function apiSendDD(sidNode){
    if(!confirm("是否将此问卷推送钉钉群？")){
        return;
    }
    // surveyId uniqueId pro
    var suid = sidNode.getAttribute("suid");
    var snt = document.getElementById("sendSurveyTitle").innerText;
    var surveyName = snt.substring(snt.indexOf("【")+1, snt.indexOf("】"));
    var sid = document.getElementById("sendSurveyTitle").getAttribute("sid");
    var uri = "action=sendDD"+"&surveyId="+sid+"&uniqueId="+suid+"&pro="+surveyName;

    var xmlHttp = new XMLHttpRequest();
    xmlHttp.open("get", "/survey/getSurveyList?"+uri, true);
    xmlHttp.onreadystatechange = function(){
        if (xmlHttp.readyState==4){
            if (xmlHttp.status==200){
                var r = JSON.parse(xmlHttp.response);
                if (r["apiStatus"] == "1"){
                    alert("推送成功")
                }else{
                    alert("获取失败")
                }
            }
        }
    };
    xmlHttp.send();
}

//更新问卷状态
function apiEditSurvey(sidNode){
    if(!confirm("关闭问卷以后将不会在页面上展示,是否要关闭？")){
        return;
    }

    var sid = sidNode.getAttribute("sid");
    var data = {
        "sid":sid
    };
    var saveData = {
        "action":"editSurvey",
        "data":data
    };
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.open("post", "/survey/saveSurvey", true);
    xmlHttp.onreadystatechange = function(){
        if (xmlHttp.readyState==4){
            if (xmlHttp.status==200){
                var r = JSON.parse(xmlHttp.response);
                if (r["apiStatus"] == "1"){
                    apiGetSurveyList();
                }else{
                    alert("获取失败")
                }
            }
        }
    };
    xmlHttp.send(JSON.stringify(saveData));
}

//生成问卷
function apiGenerateSurvey(sidNode){
    var count = Number(prompt("生成多少份？"));
    if (count < 1 || count >100){
        alert("一次只能生成1-100份");
        return;
    }
    var surveyid = sidNode.getAttribute("sid");
    var data = {
        "surveyId":surveyid,
        "count":count
    };
    var saveData = {
        "action":"generateSurvey",
        "data":data
    };

    var xmlHttp = new XMLHttpRequest();
    xmlHttp.open("post", "/survey/saveSurvey", true);
    xmlHttp.onreadystatechange = function(){
        if (xmlHttp.readyState==4){
            if (xmlHttp.status==200){
                var r = JSON.parse(xmlHttp.response);
                if (r["apiStatus"] == "1"){

                }else{
                    alert("获取失败")
                }
            }
        }
    };
    xmlHttp.send(JSON.stringify(saveData));

}

//  -----------  页面绘制  -------------

//绘制用户答卷列表
function drawAnswerList(data){
    var answerList = document.getElementById("answerList");
    var answerListHeader = document.getElementById("answerListHeader");
    answerList.innerText = "";
    answerList.appendChild(answerListHeader);

    for(var i = 0; i < data.length; i++){
        var tr = document.createElement("tr");
        tr.onclick = function(){drawUserAnswer(this)};
        tr.style.cursor = "pointer";
        //组装问卷条款与评分
        var d3 = JSON.parse(data[i][3]);
        var d4 = JSON.parse(data[i][4]);
        var mix = [];
        for(var d = 0; d < d3.length; d++){
            var cont = d3[d];
            var soc = d4[d];
            mix[d] = cont + ":" + soc + "分";
        }
        tr.setAttribute("clause", JSON.stringify(mix));
        tr.onmouseover = function(){this.style.backgroundColor = '#ffcfce'};
        tr.onmouseout = function(){this.style.backgroundColor = 'transparent'};

        var td1 = document.createElement("td");
        td1.innerText = data[i][1];
        tr.appendChild(td1);
        var td2 = document.createElement("td");
        td2.innerText = data[i][2];
        tr.appendChild(td2);
        var td3 = document.createElement("td");
        td3.innerText = data[i][5];
        tr.appendChild(td3);
        var td4 = document.createElement("td");
        var userMark = data[i][6];
        td4.setAttribute("userMark", data[i][6]);
        if(userMark.length > 20){
            userMark = userMark.substr(0, 20) + "...";
        }
        td4.innerText = userMark;
        tr.appendChild(td4);

        answerList.appendChild(tr);
    }
}

//填充左侧答卷数据
function drawUserAnswer(obj){
    var clause = JSON.parse(obj.getAttribute("clause"));
    var tdArr = obj.getElementsByTagName("td");
    var surveyName = tdArr[0].innerText;
    var userName = tdArr[1].innerText;
    var score = tdArr[2].innerText;
    var userMark = tdArr[3].getAttribute("userMark").trim();

    document.getElementById("userName").innerText = userName;
    document.getElementById("answerSurveyName").innerText = surveyName;
    document.getElementById("score").innerText = score;
    if(userMark == ""){
        userMark = "评分就是我的观点";
    }
    document.getElementById("userMark").innerText = userMark;

    //绘制条款评分
    var surveyClauseList = document.getElementById("surveyClauseList");
    surveyClauseList.innerText = "";
    for(var i = 0; i < clause.length; i++){
        var li = document.createElement("li");
        li.setAttribute("style", "background-color: rgb(255, 255, 255); height: 50px; margin-bottom: 15px;");
        var div = document.createElement("div");
        div.setAttribute("style", "text-align: center; width: 100%; font-size: 30px; color: #b2826c; margin-top: 7px");
        var clauseSize = clause[i].length;
        if(clauseSize > 10 && clauseSize <=16){
            div.style.fontSize = "25px";
        }
        if(clauseSize > 16 && clauseSize <=21){
            div.style.marginTop = "11px";
            div.style.fontSize = "20px";
        }
        if(clauseSize > 21){
            div.style.marginTop = "13px";
            div.style.fontSize = "16px";
        }
        li.appendChild(div);
        var b = document.createElement("b");
        b.innerText = clause[i];
        div.appendChild(b);
        surveyClauseList.appendChild(li);
    }
}

//绘制可用问卷列表
function drawAvailableSurveyList(sid, data){
    var availableSurveyHeader = document.getElementById("availableSurveyHeader");
    var availableSurvey = document.getElementById("availableSurvey");
    availableSurvey.innerText = "";
    availableSurvey.appendChild(availableSurveyHeader);

    for(var i = 0; i < data.length; i++){
        var trLine = document.createElement("tr");
        var td1 = document.createElement("td");
        td1.innerText = data[i];
        trLine.appendChild(td1);
        //操作栏
        var td3 = document.createElement("td");
        td3.setAttribute("suid", data[i][0]);
        var span1 = document.createElement("span");
        span1.className = "forTD";
        span1.innerText = "链接";
        span1.onclick = function(){
            var suid = this.parentNode.previousSibling.innerText;
            var url = window.location.host + "/html/surveyTemplate.html?uniqueid="+suid+"&surveyid="+sid;
            alert(url);
        };
        td3.appendChild(span1);
        var span2 = document.createElement("span");
        span2.className = "forTD";
        span2.innerText = "钉钉";
        span2.onclick = function(){
            apiSendDD(this.parentNode)
        };
        td3.appendChild(span2);
        trLine.appendChild(td3);
        availableSurvey.appendChild(trLine);
    }
}

//问卷列表绘制
function drawSurveyList(data){
    var tableheader = document.getElementById("tableheader");
    var table = document.getElementById("table");
    table.innerText = "";
    table.appendChild(tableheader);

    for(var i = 0; i < data.length; i++){
        var trLine = document.createElement("tr");
        var td1 = document.createElement("td");
        td1.innerText = (i+1).toString();
        trLine.appendChild(td1);
        var td2 = document.createElement("td");
        td2.innerText = data[i][1];
        trLine.appendChild(td2);
        //操作栏
        var td3 = document.createElement("td");
        td3.setAttribute("sid", data[i][0]);
        var span1 = document.createElement("span");
        span1.className = "forTD";
        span1.innerText = "生成";
        span1.onclick = function(){apiGenerateSurvey(this.parentNode)};
        td3.appendChild(span1);
        var span2 = document.createElement("span");
        span2.className = "forTD";
        span2.innerText = "查看";
        span2.onclick = function(){apiGetOneSurvey(this.parentNode)};
        td3.appendChild(span2);
        var span3 = document.createElement("span");
        span3.className = "forTD";
        span3.innerText = "关闭";
        span3.onclick = function(){apiEditSurvey(this.parentNode)};
        td3.appendChild(span3);
        trLine.appendChild(td3);
        table.appendChild(trLine);
    }

}

//预览进度表
/*
 <div style="width: 100%">
    <input class="survey" type="text" style="width: 80%;" placeholder="项目2"/>
    <button class="survey">-</button>
    <button class="survey">+</button>
 </div>
 */
function drawAddClause(op){
    var s_list = document.getElementById("s_list");
    var clauseDiv = document.createElement("div");
    clauseDiv.style.width = "100%";
    var clauseInput = document.createElement("input");
    clauseInput.className = "survey";
    clauseInput.style.width = "80%";
    clauseInput.type = "text";
    clauseInput.placeholder = "条款，长度不建议超过10个中文";
    clauseDiv.appendChild(clauseInput);
    if(op == 1){
        var clauseRemoveB = document.createElement("button");
        clauseRemoveB.className = "survey";
        clauseRemoveB.innerText = "-";
        clauseRemoveB.onclick = function(){drawRemoveClause(this.parentNode)};
        clauseDiv.appendChild(clauseRemoveB);
    }
    var clauseAddB = document.createElement("button");
    clauseAddB.className = "survey";
    clauseAddB.innerText = "+";
    clauseAddB.onclick = function(){drawAddClause(1)};
    clauseDiv.appendChild(clauseAddB);
    s_list.appendChild(clauseDiv);

}
function drawRemoveClause(ob){
    ob.remove();
}


//
//页面调用 数据获取，接口层与渲染层的连接
//
function controlTopDivSurvey(whichWindow, mySwitch, text){
    var topDiv = document.getElementById(whichWindow);
    if (mySwitch == "open") {
        //设置页面抬头
        topDiv.getElementsByTagName("label")[0].innerText = text;
        //初始化
        var s_list = document.getElementById("s_list");
        s_list.innerText = "";
        drawAddClause(0);

        //显示页面
        topDiv.style.marginTop = document.documentElement.scrollTop + "px";
        topDiv.style.display = "block";
    }

    //关
    if (mySwitch == "close") topDiv.style.display = "none";
}
function controlGenerateSurvey(whichWindow, mySwitch, text){
    var topDiv = document.getElementById(whichWindow);
    if (mySwitch == "open") {
        //设置页面抬头G
        topDiv.getElementsByTagName("label")[0].innerText = text;
        //初始化
        //var s_list = document.getElementById("s_list");
        //s_list.innerText = "";
        apiGetSurveyList();

        //显示页面
        topDiv.style.marginTop = document.documentElement.scrollTop + "px";
        topDiv.style.display = "block";
    }

    //关
    if (mySwitch == "close") topDiv.style.display = "none";
}
function controlSendSurvey(whichWindow, mySwitch, text){
    var topDiv = document.getElementById(whichWindow);
    if (mySwitch == "open") {
        //设置页面抬头G
        topDiv.getElementsByTagName("label")[0].innerText = text;
        //初始化
        //var s_list = document.getElementById("s_list");
        //s_list.innerText = "";
        //apiGetSurveyList();

        //显示页面
        topDiv.style.marginTop = document.documentElement.scrollTop + "px";
        topDiv.style.display = "block";
    }

    //关
    if (mySwitch == "close") topDiv.style.display = "none";
}

//弹出转换的图片层
function controlOpenPic(whichWindow, mySwitch, text){
    var topDiv = document.getElementById(whichWindow);
    if (mySwitch == "open") {
        //设置页面抬头G
        topDiv.getElementsByTagName("label")[0].innerText = text;
        //初始化

        //显示页面
        topDiv.style.marginTop = document.documentElement.scrollTop + "px";
        topDiv.style.display = "block";
    }
    //关
    if (mySwitch == "close") topDiv.style.display = "none";
}

function openPic(){
    window.scrollTo(0,0);
    document.getElementById("pic").innerText = "";
    controlOpenPic('openPic', "open", "");
    html2canvas(document.getElementById('capture')).then(function(canvas){document.getElementById('pic').appendChild(canvas);});
}

function initializeData(){
    //填充当前年份
    var da = new Date();
    document.getElementById("year").value = da.getFullYear();

    //延迟加载列表
    setTimeout(
        function(){apiShowAnswerList()},
        500
    )
}